import ImageUpload from '@/components/ImageUpload';
import RoomEditModal from '@/components/RoomEditModal';
import {
  ArrowLeftOutlined,
  HomeOutlined,
  PlusOutlined,
  TeamOutlined,
} from '@ant-design/icons';
import { useNavigate } from '@umijs/max';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  Input,
  InputNumber,
  Radio,
  Row,
  Select,
  Space,
  Tag,
  message,
} from 'antd';
import { useEffect, useState } from 'react';
import './index.less';

const { TextArea } = Input;
const { Option } = Select;

export default () => {
  const [form] = Form.useForm();
  const [rentalType, setRentalType] = useState<'whole' | 'shared'>('whole');
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  // 移除独立的 houseImages 状态，使用 Form 管理
  const [houseTags, setHouseTags] = useState<string[]>([]);

  // 合租相关状态
  const [roomInfoList, setRoomInfoList] = useState<
    Array<{
      id: string;
      roomType: string;
      orientation: string;
      innerArea: number;
      monthlyRent: number;
      rentalStatus: string;
      imageList: any[];
      sortOrder: number;
    }>
  >([]);

  // 房间编辑弹窗相关状态
  const [roomModalVisible, setRoomModalVisible] = useState(false);
  const [editingRoomIndex, setEditingRoomIndex] = useState<number | null>(null);

  // 支付周期选项
  const paymentCycleOptions = [
    { label: '月付', value: '月付' },
    { label: '季付', value: '季付' },
    { label: '半年付', value: '半年付' },
    { label: '年付', value: '年付' },
  ];

  // 出租状态选项
  const rentalStatusOptions = [
    { label: '可出租', value: '可出租' },
    { label: '已出租', value: '已出租' },
    { label: '维修中', value: '维修中' },
  ];

  // 看房时间选项
  const viewingPeriodOptions = [
    { label: '随时看房', value: '随时看房' },
    { label: '预约看房', value: '预约看房' },
    { label: '周末看房', value: '周末看房' },
  ];

  // 房源标签选项
  const houseTagOptions = [
    '近地铁',
    '精装修',
    '南北通透',
    '采光好',
    '安静',
    '有阳台',
    '有停车位',
    '有电梯',
    '近学校',
    '近商场',
  ];

  // 公共设施选项
  const commonFacilityOptions = [
    'WiFi',
    '洗衣机',
    '冰箱',
    '微波炉',
    '空调',
    '暖气',
    '热水器',
    '电视机',
    '沙发',
    '餐桌',
  ];

  // 处理出租类型变化
  const handleRentalTypeChange = (value: 'whole' | 'shared') => {
    setRentalType(value);
    // 切换类型时重置相关表单字段
    form.setFieldsValue({
      houseImages: undefined,
      houseTags: [],
      roomInfoList: [],
    });
    setHouseTags([]);
    setRoomInfoList([]);
  };

  // 处理支付周期选择变化
  const handlePaymentCycleChange = () => {
    // 重置月租金字段
    form.setFieldsValue({
      rentMoney: undefined,
    });
  };

  // 打开房间编辑弹窗
  const openRoomModal = (index?: number) => {
    if (index !== undefined) {
      setEditingRoomIndex(index);
      setRoomModalVisible(true);
    } else {
      setEditingRoomIndex(null);
      setRoomModalVisible(true);
    }
  };

  // 关闭房间编辑弹窗
  const closeRoomModal = () => {
    setRoomModalVisible(false);
    setEditingRoomIndex(null);
  };

  // 保存房间信息
  const handleRoomSave = (roomData: any) => {
    if (editingRoomIndex !== null) {
      // 编辑现有房间
      const newList = [...roomInfoList];
      newList[editingRoomIndex] = {
        ...roomData,
        sortOrder: editingRoomIndex + 1,
      };
      setRoomInfoList(newList);
    } else {
      // 添加新房间
      const newRoom = {
        ...roomData,
        id: Date.now().toString(),
        sortOrder: roomInfoList.length + 1,
      };
      setRoomInfoList([...roomInfoList, newRoom]);
    }
    closeRoomModal();
  };

  // 删除房间
  const deleteRoom = (index: number) => {
    const newList = roomInfoList.filter((_, i) => i !== index);
    setRoomInfoList(newList);
  };

  // 保存整租信息
  const handleSaveWholeRental = async (values: any) => {
    setLoading(true);
    try {
      const formData = {
        ...values,
        rentalType: 'whole',
        houseTags,
        // houseTags 已经在 values 中了，不需要单独处理
      };
      console.log('保存整租信息:', formData);
      message.success('整租信息保存成功');
      navigate(-1);
    } catch (error) {
      message.error('保存失败');
    } finally {
      setLoading(false);
    }
  };

  // 保存合租信息
  const handleSaveSharedRental = async (values: any) => {
    setLoading(true);
    try {
      const formData = {
        ...values,
        rentalType: 'shared',
        roomInfoList,
      };
      console.log('保存合租信息:', formData);
      message.success('合租信息保存成功');
      navigate(-1);
    } catch (error) {
      message.error('保存失败');
    } finally {
      setLoading(false);
    }
  };

  const handleBack = () => {
    navigate(-1);
  };

  // 数据回显功能 - 在实际项目中，这里应该从props或路由参数中获取数据
  useEffect(() => {
    // 示例：模拟回显数据
    // 如果有编辑数据，可以在这里设置表单初始值
    // form.setFieldsValue({
    //   rentalType: 'whole', // 或 'shared'
    //   paymentCycle: '月付',
    //   monthlyRent: 3000,
    //   rentalStatus: '可出租',
    //   viewingPeriod: '随时看房',
    //   moveInDate: dayjs('2024-01-01'),
    //   houseImages: [{ url: 'xxx' }],
    //   houseTags: ['近地铁', '精装修'],
    //   // 其他字段...
    // });
    // setRentalType('whole'); // 设置出租类型状态以显示选中样式
  }, []);

  return (
    <div style={{ padding: '24px' }}>
      <Card
        title={
          <Space>
            <Button
              type="text"
              icon={<ArrowLeftOutlined />}
              onClick={handleBack}
            >
              返回
            </Button>
            <span>出租信息</span>
          </Space>
        }
        style={{ maxWidth: 800, margin: '0 auto' }}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={
            rentalType === 'whole'
              ? handleSaveWholeRental
              : handleSaveSharedRental
          }
          initialValues={{
            rentalType: rentalType,
          }}
        >
          {/* 出租类型选择 */}
          <Form.Item
            name="rentalType"
            label="出租类型"
            rules={[{ required: true, message: '请选择出租类型' }]}
          >
            <Radio.Group
              value={rentalType}
              onChange={(e) => handleRentalTypeChange(e.target.value)}
              style={{ width: '100%' }}
            >
              <Row gutter={16}>
                <Col xs={24} sm={12}>
                  <div
                    className={`rental-type-card ${
                      rentalType === 'whole' ? 'selected' : ''
                    }`}
                    onClick={() => handleRentalTypeChange('whole')}
                  >
                    <Radio value="whole" style={{ display: 'none' }} />
                    <div className="rental-type-content">
                      <HomeOutlined className="rental-type-icon" />
                      <div className="rental-type-info">
                        <h4>整租</h4>
                        <p>将整套房屋出租给一个租户</p>
                      </div>
                    </div>
                  </div>
                </Col>
                <Col xs={24} sm={12}>
                  <div
                    className={`rental-type-card ${
                      rentalType === 'shared' ? 'selected' : ''
                    }`}
                    onClick={() => handleRentalTypeChange('shared')}
                  >
                    <Radio value="shared" style={{ display: 'none' }} />
                    <div className="rental-type-content">
                      <TeamOutlined className="rental-type-icon" />
                      <div className="rental-type-info">
                        <h4>合租</h4>
                        <p>将房屋按房间分别出租</p>
                      </div>
                    </div>
                  </div>
                </Col>
              </Row>
            </Radio.Group>
          </Form.Item>

          {/* 根据选择的出租类型显示对应的表单内容 */}
          {rentalType === 'whole' && (
            <>
              <h3>整租信息</h3>

              {/* 支付周期和月租金 */}
              <Form.Item
                name="paymentCycle"
                label="支付周期"
                rules={[{ required: true, message: '请选择支付周期' }]}
              >
                <Select
                  placeholder="请选择支付周期"
                  style={{ width: '100%' }}
                  onChange={handlePaymentCycleChange}
                >
                  {paymentCycleOptions.map((option) => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>

              {/* 根据选择的支付周期显示对应的月租金输入 */}

              <Form.Item
                name="monthlyRent"
                label="月租金"
                rules={[
                  {
                    required: true,
                    message: '请输入月租金',
                  },
                ]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入月租金"
                  addonBefore="¥"
                  addonAfter="元/月"
                  min={0}
                  precision={2}
                />
              </Form.Item>

              {/* 出租状态 */}
              <Form.Item
                name="rentalStatus"
                label="出租状态"
                rules={[{ required: true, message: '请选择出租状态' }]}
              >
                <Select placeholder="请选择出租状态" style={{ width: '100%' }}>
                  {rentalStatusOptions.map((option) => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>

              {/* 看房时间 */}
              <Form.Item
                name="viewingPeriod"
                label="看房时间"
                rules={[{ required: true, message: '请选择看房时间' }]}
              >
                <Select placeholder="请选择看房时间" style={{ width: '100%' }}>
                  {viewingPeriodOptions.map((option) => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>

              {/* 可入住时间 */}
              <Form.Item
                name="moveInDate"
                label="可入住时间"
                rules={[{ required: true, message: '请选择可入住时间' }]}
              >
                <DatePicker
                  style={{ width: '100%' }}
                  placeholder="请选择可入住时间"
                  format="YYYY-MM-DD"
                />
              </Form.Item>

              {/* 房源图片 */}
              <Form.Item
                label="房源图片"
                name="houseImages"
                rules={[{ required: true, message: '请上传房源图片' }]}
              >
                <div style={{ marginBottom: 8, fontSize: 12, color: '#666' }}>
                  添加室内图（必传）或视频（选传）
                </div>
                <Form.Item name="houseImages" noStyle>
                  <ImageUpload
                    maxCount={5}
                    // scene="HOUSE_IMAGE"
                  />
                </Form.Item>
              </Form.Item>

              {/* 房源标签 */}
              <Form.Item
                label="房源标签"
                rules={[{ required: true, message: '请选择房源标签' }]}
              >
                <div style={{ marginBottom: 8, fontSize: 12, color: '#666' }}>
                  丰富信息，可以更快的找到合适的租客
                </div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {houseTagOptions.map((tag) => (
                    <Tag.CheckableTag
                      key={tag}
                      checked={houseTags.includes(tag)}
                      onChange={(checked) => {
                        if (checked) {
                          setHouseTags([...houseTags, tag]);
                        } else {
                          setHouseTags(houseTags.filter((t) => t !== tag));
                        }
                      }}
                      style={{
                        padding: '4px 12px',
                        borderRadius: 16,
                        fontSize: 12,
                        backgroundColor: houseTags.includes(tag)
                          ? undefined
                          : '#f5f5f5',
                        borderColor: houseTags.includes(tag)
                          ? undefined
                          : '#d9d9d9',
                        color: houseTags.includes(tag) ? undefined : '#666',
                      }}
                    >
                      {tag}
                    </Tag.CheckableTag>
                  ))}
                </div>
              </Form.Item>
            </>
          )}

          {rentalType === 'shared' && (
            <>
              <h3>分房间出租信息</h3>

              {/* 房间管理 */}
              <Form.Item label="房间管理">
                <div style={{ marginBottom: 16 }}>
                  <Button
                    type="dashed"
                    onClick={() => openRoomModal()}
                    icon={<PlusOutlined />}
                  >
                    添加房间
                  </Button>
                </div>

                {roomInfoList.length > 0 ? (
                  <Row gutter={[16, 16]}>
                    {roomInfoList.map((room, index) => (
                      <Col xs={24} sm={12} md={8} key={room.id}>
                        <Card
                          size="small"
                          hoverable
                          cover={
                            <div style={{ height: 120, position: 'relative' }}>
                              {room.imageList.length > 0 ? (
                                <img
                                  alt={room.roomType}
                                  src={room.imageList[0]?.url}
                                  style={{
                                    width: '100%',
                                    height: '100%',
                                    objectFit: 'cover',
                                  }}
                                />
                              ) : (
                                <div
                                  style={{
                                    width: '100%',
                                    height: '100%',
                                    background: '#f5f5f5',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    color: '#999',
                                  }}
                                >
                                  暂无图片
                                </div>
                              )}
                              <div
                                style={{
                                  position: 'absolute',
                                  top: 8,
                                  right: 8,
                                  background: 'rgba(0,0,0,0.6)',
                                  color: 'white',
                                  padding: '2px 8px',
                                  borderRadius: 4,
                                  fontSize: 12,
                                }}
                              >
                                {room.rentalStatus}
                              </div>
                            </div>
                          }
                          actions={[
                            <Button
                              key="edit"
                              type="link"
                              size="small"
                              onClick={() => openRoomModal(index)}
                            >
                              修改
                            </Button>,
                            <Button
                              key="delete"
                              type="link"
                              size="small"
                              danger
                              onClick={() => deleteRoom(index)}
                            >
                              删除
                            </Button>,
                          ]}
                        >
                          <Card.Meta
                            title={`房间-${room.sortOrder} | ${room.roomType} ${room.orientation} ${room.innerArea}㎡`}
                            description={
                              <div>
                                <div>月租金: ¥{room.monthlyRent}</div>
                                <div style={{ color: '#999', fontSize: 12 }}>
                                  点击修改完善房间信息
                                </div>
                              </div>
                            }
                          />
                        </Card>
                      </Col>
                    ))}
                  </Row>
                ) : (
                  <div
                    style={{
                      border: '2px dashed #d9d9d9',
                      borderRadius: 6,
                      padding: 40,
                      textAlign: 'center',
                      color: '#999',
                    }}
                  >
                    <p>暂无房间信息</p>
                    <p style={{ fontSize: 12 }}>点击上方按钮添加房间</p>
                  </div>
                )}
              </Form.Item>

              {/* 公共区域 */}
              <Form.Item label="公共区域" name="commonAreas">
                <Select
                  mode="multiple"
                  placeholder="请选择公共区域"
                  style={{ width: '100%' }}
                >
                  <Option value="living_room">客厅</Option>
                  <Option value="kitchen">厨房</Option>
                  <Option value="bathroom">卫生间</Option>
                  <Option value="balcony">阳台</Option>
                  <Option value="dining_room">餐厅</Option>
                  <Option value="study_room">书房</Option>
                </Select>
              </Form.Item>

              {/* 公共设施 */}
              <Form.Item label="公共设施" name="commonFacilities">
                <div style={{ marginBottom: 8, fontSize: 12, color: '#666' }}>
                  选择房屋内可共享的设施
                </div>
                <Select
                  mode="multiple"
                  placeholder="请选择公共设施"
                  style={{ width: '100%' }}
                  tagRender={(props) => (
                    <Tag
                      {...props}
                      style={{
                        padding: '4px 12px',
                        borderRadius: 16,
                        fontSize: 12,
                      }}
                    >
                      {props.label}
                    </Tag>
                  )}
                >
                  {commonFacilityOptions.map((facility) => (
                    <Option key={facility} value={facility}>
                      {facility}
                    </Option>
                  ))}
                </Select>
              </Form.Item>

              {/* 合租规则 */}
              <Form.Item label="合租规则" name="rules">
                <TextArea
                  rows={3}
                  placeholder="请说明合租规则，如：作息时间、卫生要求、访客规定等"
                  maxLength={300}
                  showCount
                />
              </Form.Item>
            </>
          )}

          {/* 提交按钮 */}
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                保存
              </Button>
              <Button onClick={() => navigate(-1)}>取消</Button>
            </Space>
          </Form.Item>
        </Form>

        {/* 房间编辑弹窗 */}
        <RoomEditModal
          visible={roomModalVisible}
          onCancel={closeRoomModal}
          onOk={handleRoomSave}
          editingRoom={
            editingRoomIndex !== null ? roomInfoList[editingRoomIndex] : null
          }
          isEdit={editingRoomIndex !== null}
        />
      </Card>
    </div>
  );
};
